package com.local.coupon.rabbitmq;

import com.local.coupon.constants.CouponConstants;
import com.local.coupon.pojo.UserCouponRecord;
import com.local.coupon.service.UserCouponRecordService;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@Component
public class RabbitMQConsumer {

    @Autowired
    private UserCouponRecordService userCouponRecordService;

    /**
     * 订单使用优惠券后，更新优惠券的使用状态
     * @param userCouponRecordData
     */
    //@RabbitListener(queues = "simple.queue") //当队列不存在时，不会自动创建队列，而且会报错。
    @RabbitListener(queuesToDeclare = @Queue(CouponConstants.usedUserCouponRecordQueue) ) //当队列不存在时，自动创建队列
    public void usedUserCouponRecordQueueConsumer(String userCouponRecordData) { //userCouponRecordData : userCouponRecordId+","+orderId
        //System.out.println("接收到消息userCouponRecordData："+userCouponRecordData);
        if (Objects.nonNull(userCouponRecordData) && userCouponRecordData.length() > 0) {
            String[] arr = userCouponRecordData.split(",");
            Integer userCouponRecordId = Objects.nonNull(arr[0]) ? Integer.valueOf(arr[0]) : 0;
            Integer orderId = Objects.nonNull(arr[0]) ? Integer.valueOf(arr[1]) : 0;
            if (userCouponRecordId > 0 && orderId > 0) {
                UserCouponRecord userCouponRecord = userCouponRecordService.getById(userCouponRecordId);
                if (Objects.nonNull(userCouponRecord) && userCouponRecord instanceof UserCouponRecord) {
                    String usedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    userCouponRecord.setUseStatus(1);
                    userCouponRecord.setOrderId(orderId);
                    userCouponRecord.setUsedTime(usedTime);
                    userCouponRecord.setUpdateTime(usedTime);
                    Integer updateResult = userCouponRecordService.updateUseOrderId(userCouponRecord);
                    if (Objects.nonNull(updateResult) && updateResult > 0) {
                        //System.out.println("处理消息消息userCouponRecordData："+userCouponRecordData+" 完成");
                    } else {
                        //System.out.println("处理消息消息userCouponRecordData："+userCouponRecordData+" 失败");
                    }
                }
            }

        }
    }
}
